#include "stdafx.h"
#include "ttslib.h"
#include "genutils.h"

HRESULT tts_engine::speak(const WCHAR * pszText, const WCHAR * pszFileName)
{
	CComPtr<ISpVoice> cpVoice;
    auto hr = cpVoice.CoCreateInstance(CLSID_SpVoice);

	// generate WaveFormatEx structure, assuming the wav format is 11kHz, 16-bit, Mono
	CSpStreamFormat streamFormat;
	hr = streamFormat.AssignFormat(SPSF_11kHz16BitMono);
	
	CComPtr<ISpStream> cpWavStream;
	if (SUCCEEDED(hr))
	{
		// User SAPI helper function in sphelper.h to create a wav file
		hr = SPBindToFile(pszFileName, SPFM_CREATE_ALWAYS, &cpWavStream, &streamFormat.FormatId(), streamFormat.WaveFormatExPtr()); 
	}

	if (SUCCEEDED(hr))
	{
		hr = cpVoice->SetOutput(cpWavStream, TRUE);
	}

	if (SUCCEEDED(hr))
    {
		hr = cpVoice->Speak(pszText, SPF_ASYNC | SPF_IS_NOT_XML, 0);
    }

	// Set output back to original stream
	// Wait until the speak is finished if saving to a wav file so that cpWavStream 
	//  doesn't get released before its finished writing to the wav.
	if (SUCCEEDED(hr))
	{
		hr = cpVoice->WaitUntilDone(INFINITE);
	}
	
	if (SUCCEEDED(hr))
    {
		//hr = cpWavStream->Release();
		cpWavStream.Release();
	}

	return hr;
}